<template>
  <div class="attendance-container">
    <h1>学生请假申请</h1>
    
    <!-- 显示当前用户信息 -->
    <div class="user-info">
      <p>欢迎，{{ userProfile.fullName }} (学生)</p>
      <router-link to="/student/dashboard">返回Dashboard</router-link>
    </div>

    <div class="leave-section">
      <h2>请假申请</h2>
      <form @submit.prevent="submitLeave">
        <div class="form-group">
          <label for="startDate">请假开始日期:</label>
          <input type="date" id="startDate" v-model="leaveForm.startDate" required />
        </div>
        <div class="form-group">
          <label for="endDate">请假结束日期:</label>
          <input type="date" id="endDate" v-model="leaveForm.endDate" required />
        </div>
        <div class="form-group">
          <label for="remarks">请假原因:</label>
          <textarea id="remarks" v-model="leaveForm.remarks" rows="4" required></textarea>
        </div>
        <button type="submit" class="leave-btn">提交请假</button>
      </form>
    </div>

    <!-- 请假记录 -->
    <div class="leave-history-section">
      <h2>请假记录</h2>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="leaveHistory.length === 0" class="no-data">暂无请假记录</div>
      <div v-else>
        <div v-for="leave in leaveHistory" :key="leave.id" class="leave-item">
          <div class="leave-item-header">
            <span class="leave-status" :class="getStatusClass(leave.status)">
              {{ getStatusText(leave.status) }}
            </span>
            <span class="leave-dates">{{ leave.startDate }} 至 {{ leave.endDate }}</span>
          </div>
          <div class="leave-item-body">
            <p><strong>请假原因:</strong> {{ leave.remarks }}</p>
            <div v-if="leave.status === '1' || leave.status === '3'" class="leave-actions">
              <button @click="cancelLeave(leave.id)" class="cancel-btn">撤销申请</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>

    <!-- 成功提示 -->
    <div v-if="success" class="success-message">
      {{ success }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  name: 'StudentLeave',
  setup() {
    // 用户信息
    const userProfile = ref({});
    const studentNumber = ref(''); // 存储学号
    
    // 请假表单
    const leaveForm = ref({
      startDate: '',
      endDate: '',
      remarks: ''
    });
    
    // 请假记录
    const leaveHistory = ref([]);
    const loading = ref(false);
    
    // 状态信息
    const error = ref('');
    const success = ref('');

    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          userProfile.value = result.data;
          // 保存学号
          if (result.data.studentNumber) {
            studentNumber.value = result.data.studentNumber;
            // 加载请假记录
            await loadLeaveHistory();
          }
        } else {
          error.value = result.msg || '获取用户信息失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 获取请假记录
    const loadLeaveHistory = async () => {
      if (!studentNumber.value) return;
      
      loading.value = true;
      try {
        const response = await fetch(`/attendance/leaveStatus?studentNumber=${studentNumber.value}`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          leaveHistory.value = result.data || [];
        } else {
          error.value = result.msg || '获取请假记录失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      } finally {
        loading.value = false;
      }
    };

    // 提交请假申请
    const submitLeave = async () => {
      if (!studentNumber.value) {
        error.value = '无法获取学号信息';
        return;
      }
      
      try {
        const leaveData = {
          studentNumber: studentNumber.value,
          startDate: leaveForm.value.startDate,
          endDate: leaveForm.value.endDate,
          remarks: leaveForm.value.remarks
        };
        
        const response = await fetch('/attendance/leave', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(leaveData)
        });
        
        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '请假申请提交成功';
          // 清空表单
          leaveForm.value.startDate = '';
          leaveForm.value.endDate = '';
          leaveForm.value.remarks = '';
          // 重新加载请假记录
          await loadLeaveHistory();
        } else {
          error.value = result.msg || '请假申请提交失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 撤销请假申请
    const cancelLeave = async (leaveId) => {
      try {
        const response = await fetch(`/attendance/cancelLeave?leaveId=${leaveId}`, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '撤销申请成功';
          // 重新加载请假记录
          await loadLeaveHistory();
        } else {
          error.value = result.msg || '撤销申请失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        '1': '等待审批',
        '2': '撤销审批',
        '3': '等待系统更新',
        '4': '已完成',
        '5': '不批准'
      };
      return statusMap[status] || '未知状态';
    };

    // 获取状态样式类
    const getStatusClass = (status) => {
      const classMap = {
        '1': 'status-pending',
        '2': 'status-cancelled',
        '3': 'status-processing',
        '4': 'status-completed',
        '5': 'status-rejected'
      };
      return classMap[status] || 'status-unknown';
    };

    // 初始化
    onMounted(async () => {
      await loadUserProfile();
    });

    return {
      userProfile,
      leaveForm,
      leaveHistory,
      loading,
      error,
      success,
      submitLeave,
      cancelLeave,
      getStatusText,
      getStatusClass
    };
  }
};
</script>

<style scoped>
.attendance-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.leave-section, .leave-history-section {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
}

.leave-section h2, .leave-history-section h2 {
  margin-top: 0;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #555;
}

.form-group input, .form-group textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 16px;
}

.leave-btn, .cancel-btn {
  background-color: #FF9800;
  color: white;
  padding: 12px 30px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: background-color 0.3s;
}

.leave-btn:hover, .cancel-btn:hover {
  background-color: #F57C00;
}

.cancel-btn {
  padding: 6px 12px;
  font-size: 14px;
}

.leave-item {
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 15px;
  margin-bottom: 15px;
}

.leave-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.leave-dates {
  font-weight: bold;
  color: #555;
}

.leave-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.status-processing {
  background-color: #cce7ff;
  color: #004085;
}

.status-completed {
  background-color: #d4edda;
  color: #155724;
}

.status-rejected {
  background-color: #f8d7da;
  color: #721c24;
}

.leave-item-body p {
  margin: 5px 0;
}

.leave-actions {
  margin-top: 10px;
}

.loading, .no-data {
  text-align: center;
  padding: 20px;
  color: #666;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.success-message {
  background-color: #d4edda;
  color: #155724;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}
</style>